<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Travellings CLI</title>
  <script async src="https://umami.luochancy.com/script.js" data-website-id="23ac5682-b5b5-4013-8a32-5ceb3e598df2"></script>
  <style>
    body {
      background-color: black;
      color: white;
      font-family: Consolas, monospace;
      margin: 0;
      padding: 0;
      overflow: hidden;
    }
    #terminal {
      width: 100%;
      height: 100%;
      position: relative;
      display: flex;
      flex-direction: column;
    }
    #output-container {
      flex-grow: 1;
      overflow: auto;
      padding: 10px;
      box-sizing: border-box;
      font-size: 16px;
      white-space: nowrap;
    }
    #output {
      /* Output content goes here */
    }
    #input-container {
      display: flex;
      align-items: center;
      padding: 5px;
    }
    #prompt {
      font-size: 16px;
      margin-right: 5px;
    }
    #input {
      background-color: transparent;
      color: white;
      border: none;
      outline: none;
      font-size: 16px;
      flex-grow: 1;
      white-space: nowrap;
    }
  </style>
</head>
<body>
  <div id="terminal">
    <div id="output-container">
      <div id="output">
        <pre>________                         _______________                       
___  __/____________ ___   _________  /__  /__(_)_____________ ________
__  /  __  ___/  __ `/_ | / /  _ \_  /__  /__  /__  __ \_  __ `/_  ___/
_  /   _  /   / /_/ /__ |/ //  __/  / _  / _  / _  / / /  /_/ /_(__  ) 
/_/    /_/    \__,_/ _____/ \___//_/  /_/  /_/  /_/ /_/_\__, / /____/  
                                                       /____/          <br>Travellings CLI [Version 1.49]<br>(C) Travellings-link Project. All rights reserved. Made by BLxcwg666 with love.<br>Enter 'help' to get the commands.</pre>
      </div>
    </div>
    <div id="input-container">
      <span id="prompt" contenteditable="false">C:\Travellings ></span>
      <span id="input" contenteditable="true" autofocus></span>
    </div>
  </div>

  <script>
    const terminal = document.getElementById("terminal");
    const input = document.getElementById("input");
    const output = document.getElementById("output");
    const prompt = document.getElementById("prompt");

    let isTravellingMode = false;
    let selectedDestination = null;
    const history = []; // Array to store command history
    let historyIndex = -1; // Index to keep track of the current position in history

    input.addEventListener("keydown", function (event) {
      if (event.key === "Enter") {
        event.preventDefault();
        const command = input.textContent.trim();

        if (isTravellingMode) {
          handleTravellingInput(command);
        } else {
          if (command !== "") {
            history.push(command); // Store the command in history
            historyIndex = history.length; // Reset history index

            handleRegularInput(command);
          } else {
            // If no command is entered, display the prompt only
            appendToTerminal(prompt.textContent);
            input.textContent = "";
            input.focus();
          }
        }
      } else if (event.key === "ArrowUp") {
        // Handle the "Arrow Up" key to navigate command history
        if (historyIndex > 0) {
          historyIndex--;
          input.textContent = history[historyIndex];
        }
      } else if (event.key === "ArrowDown") {
        // Handle the "Arrow Down" key to navigate command history
        if (historyIndex < history.length - 1) {
          historyIndex++;
          input.textContent = history[historyIndex];
        } else if (historyIndex === history.length - 1) {
          // Clear the input if we're at the latest history entry
          input.textContent = "";
        }
      }
    });

    function handleRegularInput(command) {
      if (command.toLowerCase() === "clear") {
        output.innerHTML = "";
        output.scrollTop = 0;
      } else if (command.toLowerCase() === "travellings" || command.toLowerCase() === "t") {
        isTravellingMode = true;
        fetchNewDestination();
      } else if (command.toLowerCase() === "date") {
        const currentDate = new Date().toLocaleString("zh-CN", { timeZone: "Asia/Shanghai" });
        appendToTerminal("C:\\Travellings > " + command);
        appendToTerminal(currentDate);
      } else if (command.toLowerCase() === "help") {
        appendToTerminal("C:\\Travellings > " + command);
        appendToTerminal("Commands：<br>t               开始穿梭！<br>cmd             输出版权信息<br>help            输出帮助菜单<br>echo            输出文字<br>date            输出当前时间<br>clear           清空历史记录<br>settings           前往开往偏好设置<br>travellings     开始穿梭吧！");
      } else if (command.toLowerCase() === "cmd") {
        // Print the title
        appendToTerminal("Travellings CLI [Version 1.49]<br>(C) Travellings-link Project. All rights reserved.");
      } else if (command.toLowerCase().startsWith("echo ")) {
        const text = command.slice(5);
        appendToTerminal("C:\\Travellings > " + command);
        appendToTerminal(text);
      } else if (command.toLowerCase() === "settings") {
        appendToTerminal("C:\\Travelling > " + command);
        appendToTerminal("正在前往开往偏好设置...")
        location.href = "./preference";
      } else {
        appendToTerminal("C:\\Travellings > " + command);
        appendToTerminal("Command not found: " + command);
      }

      input.textContent = "";
      input.focus();
    }

    function handleTravellingInput(choice) {
      choice = choice.toLowerCase();

      if (choice === "y") {
        if (selectedDestination && selectedDestination.url) {
          window.open(selectedDestination.url, "_blank");
          appendToTerminal("请做出你的选择 > Y");
          appendToTerminal("即将发车...");
        }
        isTravellingMode = false;

        // Reset the prompt
        prompt.textContent = "C:\\Travellings >";
        input.textContent = "";
        input.focus();
      } else if (choice === "n") {
        fetchNewDestination();
      } else if (choice === "e") {
        isTravellingMode = false;

        // Reset the prompt
        prompt.textContent = "C:\\Travellings >";
        input.textContent = "";
        input.focus();
        appendToTerminal("请做出你的选择 > E");
        appendToTerminal("已取消本次穿梭");
      } else {
        appendToTerminal("C:\\Travellings > " + choice);
        appendToTerminal("无效的选择");

        // Change the prompt
        prompt.textContent = "请做出你的选择 >";
        input.textContent = "";
        input.focus();
      }
    }

    function fetchNewDestination() {
      const tag = localStorage.getItem("t_preference_tag") || "tech";
    fetch("https://api.travellings.cn/random?tag=" + tag)
        .then(response => response.json())
        .then(data => {
            if (data.success && data.data.length > 0) {
                selectedDestination = data.data[0];

                // Clear previous destination information
                output.innerHTML = "";

                // Display new destination information
                appendToTerminal("Go to Travel！");
                appendToTerminal(`即将开往：${selectedDestination.name}（${selectedDestination.url}）`);
                appendToTerminal("输入 'Y' 出发，输入 'N' 重新选择目的地，输入 'E' 退出。");

                // Change the prompt
                prompt.textContent = "请做出你的选择 >";
                input.textContent = "";
                input.focus();
            } else {
                // Handle the case where the request was not successful
                console.error("出错了呜呜呜~ 从API获取数据时发生错误:", data);
            }
        })
        .catch(error => {
            console.error("出错了呜呜呜~ 请求API时发生错误:", error);
        });
}

    function appendToTerminal(text) {
      const pre = document.createElement("pre");
      pre.innerHTML = text;
      output.appendChild(pre);
      output.scrollTop = output.scrollHeight;
    }
  </script>
</body>
</html>
